﻿using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.Synchronization.Validation.Handlers.Common;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;

namespace Sustainalytics.Synchronization.Validation.Handlers.Core
{
    public class CoreCorporateDataLoader
    {
        private readonly IMongoCollection<CompanyProfileResearchState> mongoCollection;
        private readonly CoreCompanies coreCompanies;
        private readonly WhiteListCompanies whiteListCompanies;

        public CoreCorporateDataLoader(IMongoCollection<CompanyProfileResearchState> mongoCollection, CoreCompanies coreCompanies, WhiteListCompanies whiteListCompanies)
        {
            this.mongoCollection = mongoCollection;
            this.coreCompanies = coreCompanies;
            this.whiteListCompanies = whiteListCompanies;
        }

        public async Task LoadAsync()
        {
            var values = await mongoCollection.Find(Builders<CompanyProfileResearchState>.Filter.Where(x => x.CoreEsgResearchState.ResearchState == ResearchState.ResearchAvailable))
                 .Project(x => new
                 {
                     Id = x.Id,
                     CapitalIqId = x.CapitalIqId
                 }).ToListAsync().ConfigureAwait(false);

            foreach (var value in values)
            {
                if (!coreCompanies.Contains(value.Id) &&
                    !whiteListCompanies.Exists(x => x.CapitalIqId == value.CapitalIqId && x.ResearchProduct == BusinessResearchProduct.Core))
                    coreCompanies.Add(value.Id);
            }
        }
    }
}
